<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/13
 * Time: 12:57
 */

namespace App\Model\Account;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;

class Administration extends Model
{
    /**
     * 平台管理者账号列表
     */
    public static function adminList($pageLimit, $where = [])
    {
        $list = DB::table('account_number_manager')
            ->leftJoin('user', 'anm_id', '=', 'u_b_id')
            ->where($where)
            ->where('u_type', 2)
            ->orderBy('anm_id', 'desc')
            ->select('anm_id', 'u_account_number', 'anm_branch_name', 'anm_branch_address', 'anm_legal', 'anm_legal_phone', 'anm_principal',
                'anm_principal_phone', 'anm_business_license', 'anm_identity_face', 'anm_identity_side', 'anm_current_grade',
                'anm_current_years',  DB::raw('from_unixtime(anm_current_buytime) AS anm_current_buytime'),
                DB::raw('from_unixtime(anm_current_reminding) AS anm_current_reminding'),
                DB::raw('from_unixtime(anm_expirytime) AS anm_expirytime'),  'anm_status')
            ->paginate($pageLimit);
        if (sizeof($list) == 0){
            return false;
        }
        return $list;
    }
    //统计中介的数量
    public static function adminCount($where)
    {
        return DB::table('account_number_manager')->where($where)->count();
    }
    //统计中介缴费钱数总和
    public static function allmoney($map)
    {
        $allmoney = DB::table('number_money')->where('nm_type', 2)->where($map)->value(DB::raw('sum(nm_money)'));
        if (!$allmoney) {
           return 0;
        }
        return $allmoney;
    }

    //根据中介ID  查询中介的缴费记录列表
    public static function payList($id, $pageLimit)
    {
        $list = DB::table('number_money')
            ->leftJoin('admin as ca', 'nm_admin_id', '=', 'ca.a_id')
            ->leftJoin('admin as sa', 'nm_uid', '=', 'sa.a_id')
            ->leftJoin('account_price', 'nm_ap_id', '=', 'ap_id')
            ->leftJoin('account_number_manager', 'nm_anm_id', '=', 'anm_id')
            ->where('nm_anm_id', $id)
            ->orderBy('anm_id', 'desc')
            ->select('nm_id', 'anm_branch_name', 'nm_money', DB::raw('from_unixtime(nm_create_time) AS nm_create_time'),
                'ca.a_user_name as operator', 'ap_name', 'nm_status', 'nm_type',
                DB::raw('IFNULL(h_sa.a_user_name, \'\') as examine'),
                DB::raw('from_unixtime(nm_update_time) AS nm_update_time')
                )
            ->paginate($pageLimit);
        if (sizeof($list) == 0){
            return false;
        }
        return $list;
    }

    //添加中介管理账号
    public static function adminAdd($params)
    {
        //根据购买的等级    年限  计算价钱
        $price = floatval(DB::table('account_price')->where('ap_id', intval($params['anm_grade']))->value('ap_price'));
        $money = $price*$params['anm_years'];

        //根据年限  计算过期时间  提醒续费时间
        $time = time();
        $expirytime = strtotime("+".intval($params['anm_years'])." year");
        $reminding  = $expirytime - 30*24*60*60;
        //开启事务
        DB::beginTransaction();
        //添加中介信息
        $anmId = DB::table('account_number_manager')->insertGetId([
            'anm_branch_name'             =>  $params['anm_branch_name'],
            'anm_branch_address'          =>  $params['anm_branch_address'],
            'anm_legal'                   =>  $params['anm_legal'],
            'anm_legal_phone'             =>  $params['anm_legal_phone'],
            'anm_principal'               =>  $params['anm_principal'],
            'anm_principal_phone'         =>  $params['anm_principal_phone'],
            'anm_business_license'        =>  $params['anm_business_license'],
            'anm_identity_face'           =>  $params['anm_identity_face'],
            'anm_identity_side'           =>  $params['anm_identity_side'],
            'anm_current_grade'           =>  $params['anm_grade'],
            'anm_current_years'           =>  $params['anm_years'],
            'anm_current_buytime'         =>  $time,
            'anm_current_reminding'       =>  $reminding,
            'anm_expirytime'              =>  $expirytime,
            'anm_status'                  =>  2,
            'anm_update_time'             =>  $time,
            'anm_buytime'                 =>  $time
        ]);
        //添加中介缴费金额信息
        $nmId = DB::table('number_money')->insertGetId([
            'nm_anm_id'      =>  $anmId,
            'nm_money'       =>  $money,
            'nm_years'       =>  $params['anm_years'],
            'nm_admin_id'    =>  Cache::get($params['admintoken']), //操作人ID
            'nm_ap_id'       =>  intval($params['anm_grade']),
            'nm_status'      =>  1,
            'nm_type'        =>  1,
            'nm_create_time' =>  $time,
        ]);

        //添加中介首账号user
        $uId = DB::table('user')->insertGetId([
            'u_b_id'            =>     $anmId,
            'u_username'        =>     $params['anm_legal'],
            'u_account_number'  =>     str_pad($anmId, 8,0,STR_PAD_LEFT),
            'u_password'        =>     Hash::make(123456),
            'u_type'            =>      2,
            'u_status'          =>      2,
            'created_at'        =>      $time,
            'updated_at'        =>      $time,
            'is_del'            =>      0,
        ]);
        if($anmId  && $nmId  && $uId){
            DB::commit();
            return true;
        } else {
            DB::rollback();
            return false;
        }
    }

    /**审核通过     禁用启用  中介公司的所有账号
     * @param $cid  中介公司的ID
     */
    public static function updateCompanyStatus($cid, $status)
    {
        $time = time();
        if ($status == 1) {
            $status = 2;
        } elseif ($status == 2) {
            $status = 1;
        } else {
             return -1;
        }

        return DB::table('account_number_manager')->where('anm_id', $cid)->update([
                'anm_status' => $status,
                'anm_update_time' => $time
        ]);
    }

    /**公司员工给中介公司续费
     * @param $params
     * @return mixed
     */
    public static function renewTheAgency($params)
    {
        $time = time();
        //根据购买的等级    年限  计算价钱
        $price = floatval(DB::table('account_price')->where('ap_id', intval($params['anm_grade']))->value('ap_price'));
        $money = $price*$params['anm_years'];
        return DB::table('number_money')->insertGetId([
            'nm_anm_id'           =>   intval($params['anm_id']),
            'nm_money'             =>   $money,
            'nm_years'            =>   intval($params['anm_years']),
            'nm_admin_id'         =>   Cache::get($params['admintoken']),
            'nm_ap_id'            =>   intval($params['anm_grade']),
            'nm_status'           =>   2,
            'nm_type'             =>   1,
            'nm_create_time'       =>   $time
        ]);
    }




    //中介公司续费 添加续费记录
    public static function userRenew($data)
    {
        $params = DB::table('number_money')->where('nm_id', $data['nm_id'])->select('*')->first();
        if ($params->nm_type == 1) {
            //根据购买的等级    年限  计算价钱
//            $price = floatval(DB::table('account_price')->where('ap_id', $params->r_set_meal)->value('ap_price'));
//            if(!$price) {
//                return false;
//            }
//            $money = $price*$params->r_years;
//            $money =  $params->nm_money;//购买的金额
            $anmId = $params->nm_anm_id;//中介公司ID
            //根据中介公司的ID  查询中介公司上次的到期时间
            $lastInfo = DB::table('account_number_manager')
                ->where('anm_id', $anmId)
                ->select('anm_current_grade', 'anm_current_years', 'anm_current_buytime', 'anm_current_reminding', 'anm_expirytime')
                ->first();
            $lastTime = $lastInfo->anm_expirytime;
            //根据年限  计算过期时间  提醒续费时间
            $time = time();
            if ($lastTime >= $time) {
                //提前续费
                $expirytime = strtotime("+".$params->nm_years." year", $lastTime);
            } else {
                //过期续费
                $expirytime = strtotime("+".$params->nm_years." year");
            }
            $reminding  = $expirytime - 30*24*60*60;
            //开启事务
            DB::beginTransaction();
            $updaterId = DB::table('number_money')->where('nm_id', $data['nm_id'])->update([
                'nm_type'      => 2,
                'nm_uid'       => Cache::get($data['admintoken']),
                'nm_update_time' => $time
            ]);

            $updateId = DB::table('account_number_manager')->where('anm_id', $anmId)->update([
                'anm_current_grade'           =>   $params->nm_ap_id,
                'anm_current_years'           =>   $params->nm_years,
                'anm_current_buytime'         =>   $time,
                'anm_current_reminding'       =>   $reminding,
                'anm_expirytime'              =>   $expirytime,
            ]);

            if($updaterId && $updateId){
                DB::commit();
                return true;
            } else {
                DB::rollback();
                return false;
            }
        } else {
            return false;
        }

    }

    /**查询出来已经过期的中介公司《定时器》
     * @return bool
     */
    public static function getExpiredAccount()
    {
        $time = time();
        $data = DB::table('account_number_manager')
            ->where('anm_status', 1)
            ->where('anm_expirytime', '<=', $time)
            ->select('anm_id')
            ->get();
        if (sizeof($data) == 0) {
            return false;
        }
        return $data;
    }

    /**根据过期未续费的中介公司的ID   修改中介公司为过期未续费状态
     * @param $data
     */
    public static function updateAllUserStatus($data)
    {
        $anmId  = $data->anm_id;
        DB::table('account_number_manager')->where('anm_id',$anmId)->update([
            'anm_status'      => 3,
            'anm_update_time' => time()
        ]);
    }

    /**添加完中介公司的资料 创建完该中介的系列表   审核通过该中介公司  和中介老板的账号
     * @param $id 中介公司的ID
     */
    public static function examineAccount($params)
    {
        $time = time();
        //开启事务
        DB::beginTransaction();
        //修改该中介公司的账号的状态为启用
        $anmId = DB::table('account_number_manager')->where('anm_id', $params['nm_id'])->update([
            'anm_status'            => 1,
            'anm_update_time'       => $time
        ]);
        //修改该中介公司首次缴费记录的状态
        $nmId = DB::table('number_money')->where('nm_anm_id', $params['nm_id'])->where('nm_status', 1)->update([
            'nm_type'   => 2,
            'nm_uid'    => Cache::get($params['admintoken']),
            'nm_update_time'   =>  $time
        ]);
        //修改该中介公司老板账号的状态为正常
        $uId = DB::table('user')->where('u_b_id', $params['nm_id'])->where('u_type', 2)->update([
            'u_status'         => 1,
            'updated_at'       => $time
        ]);
        if ($anmId && $nmId && $uId) {
            DB::commit();
            return true;
        } else {
            DB::rollback();
            return false;
        }

    }
}